package com.happy.study.controller;

import com.alibaba.fastjson.JSONObject;
import com.happy.study.entity.DataEntity;
import com.happy.study.servier.IDataService;
import com.happy.study.util.ResultBody;
import com.happy.study.util.StateEnum;
import com.happy.study.util.StateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping ( "data" )
@Slf4j
public class DataController {

    @Resource
    private IDataService iDataService;

    @RequestMapping ( "queryList" )
    public ResultBody queryList ( String dataEntity ) {
        DataEntity data = JSONObject.parseObject ( dataEntity, DataEntity.class );
        List<DataEntity> dataEntities = iDataService.queryList ( data );
        return ResultBody.success ( dataEntities, iDataService.queryCount ( data ) );
    }

    /**
     * 下载资料
     *
     * @param id
     * @return
     */
    @GetMapping ( "download/{id}" )
    public ResultBody download ( @PathVariable String id, HttpServletResponse response ) throws UnsupportedEncodingException {
        log.info ( "id = [{}]", id );
        DataEntity dataEntity = new DataEntity ();
        dataEntity.setId ( Integer.parseInt ( id ) );
        DataEntity data = iDataService.querySingle ( dataEntity );
        if ( data == null ) {
            throw new StateException ( StateEnum.RESULT_NULL_EXCE );
        }
        data.setDownNum ( data.getDownNum () + 1 );
        iDataService.updateSingle ( data );
        File file = new File ( data.getFileDisk () );
        // 如果文件名存在，则进行下载
        if ( file.exists () ) {
            // 配置文件下载
            response.setHeader ( "content-type", "application/octet-stream" );
            response.setContentType ( "application/octet-stream" );
            // 下载文件能正常显示中文
            response.setHeader ( "Content-Disposition", "attachment;filename=" + URLEncoder.encode ( data.getTitle () + "." + data.getFileDisk ().substring ( data.getFileDisk ().lastIndexOf ( "." ) + 1 ), "UTF-8" ) );
            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream ( file );
                bis = new BufferedInputStream ( fis );
                OutputStream os = response.getOutputStream ();
                int i = bis.read ( buffer );
                while ( i != - 1 ) {
                    os.write ( buffer, 0, i );
                    i = bis.read ( buffer );
                }
                System.out.println ( "Download the song successfully!" );
            } catch ( Exception e ) {
                System.out.println ( "Download the song failed!" );
            } finally {
                if ( bis != null ) {
                    try {
                        bis.close ();
                    } catch ( IOException e ) {
                        e.printStackTrace ();
                    }
                }
                if ( fis != null ) {
                    try {
                        fis.close ();
                    } catch ( IOException e ) {
                        e.printStackTrace ();
                    }
                }
            }
        }
        return null;
    }

}
